home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python1.4_Source / Python / import.c < prev    next >
C/C++ Source or Header  |  1998-06-24  |  22KB  |  1,058 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Module definition and import implementation */
  33.  
  34. #include "allobjects.h"
  35.  
  36. /* XXX Some of the following are duplicate with allobjects.h... */
  37. #include "node.h"
  38. #include "token.h"
  39. #include "graminit.h"
  40. #include "import.h"
  41. #include "errcode.h"
  42. #include "sysmodule.h"
  43. #include "bltinmodule.h"
  44. #include "pythonrun.h"
  45. #include "marshal.h"
  46. #include "compile.h"
  47. #include "eval.h"
  48. #include "osdefs.h"
  49. #include "importdl.h"
  50. #ifdef macintosh
  51. /* 'argument' is a grammar symbol, but also used in some mac header files */
  52. #undef argument
  53. #include "macglue.h"
  54. #endif
  55.  
  56. #ifdef _AMIGA
  57. #include <proto/dos.h>
  58. #endif
  59.  
  60. #include "protos/import_protos.h"
  61.  
  62. extern long getmtime Py_PROTO((char*)); /* In getmtime.c */
  63.  
  64. /* Magic word to reject .pyc files generated by other Python versions */
  65. /* Change for each incompatible change */
  66. /* The value of CR and LF is incorporated so if you ever read or write
  67.    a .pyc file in text mode the magic number will be wrong; also, the
  68.    Apple MPW compiler swaps their values, botching string constants */
  69. /* XXX Perhaps the magic number should be frozen and a version field
  70.    added to the .pyc file header? */
  71. #define MAGIC (5892 | ((long)'\r'<<16) | ((long)'\n'<<24))
  72.  
  73. object *import_modules; /* This becomes sys.modules */
  74.  
  75.  
  76. /* Initialize things */
  77.  
  78. void
  79. initimport()
  80. {
  81.     if (import_modules != NULL)
  82.         fatal("duplicate initimport() call");
  83.     if ((import_modules = newdictobject()) == NULL)
  84.         fatal("no mem for dictionary of modules");
  85. }
  86.  
  87.  
  88. /* Un-initialize things, as good as we can */
  89.  
  90. void
  91. doneimport()
  92. {
  93.     if (import_modules != NULL) {
  94.         object *tmp = import_modules;
  95.         import_modules = NULL;
  96.         /* This deletes all modules from sys.modules.
  97.            When a module is deallocated, it in turn clears its dictionary,
  98.            thus hopefully breaking any circular references between modules
  99.            and between a module's dictionary and its functions.
  100.            Note that "import" will fail while we are cleaning up.
  101.            */
  102.         mappingclear(tmp);
  103.         DECREF(tmp);
  104.     }
  105. }
  106.  
  107.  
  108. /* Helper for pythonrun.c -- return magic number */
  109.  
  110. long
  111. get_pyc_magic()
  112. {
  113.     return MAGIC;
  114. }
  115.  
  116.  
  117. /* Helper for sysmodule.c -- return modules dictionary */
  118.  
  119. object *
  120. get_modules()
  121. {
  122.     return import_modules;
  123. }
  124.  
  125.  
  126. /* Get the module object corresponding to a module name.
  127.    First check the modules dictionary if there's one there,
  128.    if not, create a new one and insert in in the modules dictionary.
  129.    Because the former action is most common, THIS DOES NOT RETURN A
  130.    'NEW' REFERENCE! */
  131.  
  132. object *
  133. add_module(name)
  134.     char *name;
  135. {
  136.     object *m;
  137.  
  138.     if (import_modules == NULL) {
  139.         err_setstr(SystemError, "sys.modules has been deleted");
  140.         return NULL;
  141.     }
  142.     if ((m = dictlookup(import_modules, name)) != NULL &&
  143.         is_moduleobject(m))
  144.         return m;
  145.     m = newmoduleobject(name);
  146.     if (m == NULL)
  147.         return NULL;
  148.     if (dictinsert(import_modules, name, m) != 0) {
  149.         DECREF(m);
  150.         return NULL;
  151.     }
  152.     DECREF(m); /* Yes, it still exists, in modules! */
  153.  
  154.     return m;
  155. }
  156.  
  157.  
  158. /* Execute a code object in a module and return the module object
  159.    WITH INCREMENTED REFERENCE COUNT */
  160.  
  161. object *
  162. exec_code_module(name, co)
  163.     char *name;
  164.     object *co;
  165. {
  166.     object *m, *d, *v;
  167.  
  168.     m = add_module(name);
  169.     if (m == NULL)
  170.         return NULL;
  171.     d = getmoduledict(m);
  172.     if (dictlookup(d, "__builtins__") == NULL) {
  173.         if (dictinsert(d, "__builtins__", getbuiltins()) != 0)
  174.             return NULL;
  175.     }
  176.     /* Remember the filename as the __file__ attribute */
  177.     if (dictinsert(d, "__file__", ((codeobject *)co)->co_filename) != 0)
  178.         err_clear(); /* Not important enough to report */
  179.     v = eval_code((codeobject *)co, d, d); /* XXX owner? */
  180.     if (v == NULL)
  181.         return NULL;
  182.     DECREF(v);
  183.     INCREF(m);
  184.  
  185.     return m;
  186. }
  187.  
  188.  
  189. /* Given a pathname for a Python source file, fill a buffer with the
  190.    pathname for the corresponding compiled file.  Return the pathname
  191.    for the compiled file, or NULL if there's no space in the buffer.
  192.    Doesn't set an exception. */
  193.  
  194. static char *
  195. make_compiled_pathname(pathname, buf, buflen)
  196.     char *pathname;
  197.     char *buf;
  198.     int buflen;
  199. {
  200.     int len;
  201.  
  202.     len = strlen(pathname);
  203.     if (len+2 > buflen)
  204.         return NULL;
  205.     strcpy(buf, pathname);
  206.     strcpy(buf+len, "c");
  207.  
  208.     return buf;
  209. }
  210.  
  211.  
  212. /* Given a pathname for a Python source file, its time of last
  213.    modification, and a pathname for a compiled file, check whether the
  214.    compiled file represents the same version of the source.  If so,
  215.    return a FILE pointer for the compiled file, positioned just after
  216.    the header; if not, return NULL.
  217.    Doesn't set an exception. */
  218.  
  219. static FILE *
  220. check_compiled_module(pathname, mtime, cpathname)
  221.     char *pathname;
  222.     long mtime;
  223.     char *cpathname;
  224. {
  225.     FILE *fp;
  226.     long magic;
  227.     long pyc_mtime;
  228.  
  229.     fp = fopen(cpathname, "rb");
  230.     if (fp == NULL)
  231.         return NULL;
  232.     magic = rd_long(fp);
  233.     if (magic != MAGIC) {
  234.         if (verbose)
  235.             fprintf(stderr, "# %s has bad magic\n", cpathname);
  236.         fclose(fp);
  237.         return NULL;
  238.     }
  239.     pyc_mtime = rd_long(fp);
  240.     if (pyc_mtime != mtime) {
  241.         if (verbose)
  242.             fprintf(stderr, "# %s has bad mtime\n", cpathname);
  243.         fclose(fp);
  244.         return NULL;
  245.     }
  246.     if (verbose)
  247.         fprintf(stderr, "# %s matches %s\n", cpathname, pathname);
  248.     return fp;
  249. }
  250.  
  251.  
  252. /* Read a code object from a file and check it for validity */
  253.  
  254. static codeobject *
  255. read_compiled_module(fp)
  256.     FILE *fp;
  257. {
  258.     object *co;
  259.  
  260.     co = rd_object(fp);
  261.     /* Ugly: rd_object() may return NULL with or without error */
  262.     if (co == NULL || !is_codeobject(co)) {
  263.         if (!err_occurred())
  264.             err_setstr(ImportError,
  265.                    "Non-code object in .pyc file");
  266.         XDECREF(co);
  267.         return NULL;
  268.     }
  269.     return (codeobject *)co;
  270. }
  271.  
  272.  
  273. /* Load a module from a compiled file, execute it, and return its
  274.    module object WITH INCREMENTED REFERENCE COUNT */
  275.  
  276. static object *
  277. load_compiled_module(name, cpathname, fp)
  278.     char *name;
  279.     char *cpathname;
  280.     FILE *fp;
  281. {
  282.     long magic;
  283.     codeobject *co;
  284.     object *m;
  285.  
  286.     magic = rd_long(fp);
  287.     if (magic != MAGIC) {
  288.         err_setstr(ImportError, "Bad magic number in .pyc file");
  289.         return NULL;
  290.     }
  291.     (void) rd_long(fp);
  292.     co = read_compiled_module(fp);
  293.     if (co == NULL)
  294.         return NULL;
  295.     if (verbose)
  296.         fprintf(stderr, "import %s # precompiled from %s\n",
  297.             name, cpathname);
  298.     m = exec_code_module(name, (object *)co);
  299.     DECREF(co);
  300.  
  301.     return m;
  302. }
  303.  
  304. /* Parse a source file and return the corresponding code object */
  305.  
  306. static codeobject *
  307. parse_source_module(pathname, fp)
  308.     char *pathname;
  309.     FILE *fp;
  310. {
  311.     codeobject *co;
  312.     node *n;
  313.  
  314.     n = parse_file(fp, pathname, file_input);
  315.     if (n == NULL)
  316.         return NULL;
  317.     co = compile(n, pathname);
  318.     freetree(n);
  319.  
  320.     return co;
  321. }
  322.  
  323.  
  324. /* Write a compiled module to a file, placing the time of last
  325.    modification of its source into the header.
  326.    Errors are ignored, if a write error occurs an attempt is made to
  327.    remove the file. */
  328.  
  329. static void
  330. write_compiled_module(co, cpathname, mtime)
  331.     codeobject *co;
  332.     char *cpathname;
  333.     long mtime;
  334. {
  335.     FILE *fp;
  336.  
  337.     fp = fopen(cpathname, "wb");
  338.     if (fp == NULL) {
  339.         if (verbose)
  340.             fprintf(stderr,
  341.                 "# can't create %s\n", cpathname);
  342.         return;
  343.     }
  344.     wr_long(MAGIC, fp);
  345.     /* First write a 0 for mtime */
  346.     wr_long(0L, fp);
  347.     wr_object((object *)co, fp);
  348.     if (ferror(fp)) {
  349.         if (verbose)
  350.             fprintf(stderr, "# can't write %s\n", cpathname);
  351.         /* Don't keep partial file */
  352.         fclose(fp);
  353.         (void) unlink(cpathname);
  354.         return;
  355.     }
  356.     /* Now write the true mtime */
  357.     fseek(fp, 4L, 0);
  358.     wr_long(mtime, fp);
  359.     fflush(fp);
  360.     fclose(fp);
  361.     if (verbose)
  362.         fprintf(stderr, "# wrote %s\n", cpathname);
  363. #ifdef macintosh
  364.     setfiletype(cpathname, 'Pyth', 'PYC ');
  365. #endif
  366. }
  367.  
  368.  
  369. /* Load a source module from a given file and return its module
  370.    object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
  371.    byte-compiled file, use that instead. */
  372.  
  373. static object *
  374. load_source_module(name, pathname, fp)
  375.     char *name;
  376.     char *pathname;
  377.     FILE *fp;
  378. {
  379.     long mtime;
  380.     FILE *fpc;
  381.     char buf[MAXPATHLEN+1];
  382.     char *cpathname;
  383.     codeobject *co;
  384.     object *m;
  385.  
  386.     mtime = getmtime(pathname);
  387.     cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1);
  388.     if (cpathname != NULL &&
  389.         (fpc = check_compiled_module(pathname, mtime, cpathname))) {
  390.         co = read_compiled_module(fpc);
  391.         fclose(fpc);
  392.         if (co == NULL)
  393.             return NULL;
  394.         if (verbose)
  395.             fprintf(stderr, "import %s # precompiled from %s\n",
  396.                 name, cpathname);
  397.     }
  398.     else {
  399.         co = parse_source_module(pathname, fp);
  400.         if (co == NULL)
  401.             return NULL;
  402.         if (verbose)
  403.             fprintf(stderr, "import %s # from %s\n",
  404.                 name, pathname);
  405.         write_compiled_module(co, cpathname, mtime);
  406.     }
  407.     m = exec_code_module(name, (object *)co);
  408.     DECREF(co);
  409.  
  410.     return m;
  411. }
  412.  
  413.  
  414. /* Search the path (default sys.path) for a module.  Return the
  415.    corresponding filedescr struct, and (via return arguments) the
  416.    pathname and an open file.  Return NULL if the module is not found. */
  417.  
  418. static struct filedescr *
  419. find_module(name, path, buf, buflen, p_fp)
  420.     char *name;
  421.     object *path;
  422.     /* Output parameters: */
  423.     char *buf;
  424.     int buflen;
  425.     FILE **p_fp;
  426. {
  427.     int i, npath, len, namelen;
  428.     struct filedescr *fdp;
  429.     FILE *fp = NULL;
  430.  
  431. #ifdef MS_COREDLL
  432.     if ((fp=PyWin_FindRegisteredModule(name, &fdp, buf, buflen))!=NULL) {
  433.         *p_fp = fp;
  434.         return fdp;
  435.     }
  436. #endif
  437.  
  438.  
  439.     if (path == NULL)
  440.         path = sysget("path");
  441.     if (path == NULL || !is_listobject(path)) {
  442.         err_setstr(ImportError,
  443.                "sys.path must be a list of directory names");
  444.         return NULL;
  445.     }
  446.     npath = getlistsize(path);
  447.     namelen = strlen(name);
  448.     for (i = 0; i < npath; i++) {
  449.         object *v = getlistitem(path, i);
  450.         if (!is_stringobject(v))
  451.             continue;
  452.         len = getstringsize(v);
  453.         if (len + 2 + namelen + import_maxsuffixsize >= buflen)
  454.             continue; /* Too long */
  455.         strcpy(buf, getstringvalue(v));
  456.         if (strlen(buf) != len)
  457.             continue; /* v contains '\0' */
  458. #ifdef macintosh
  459.         if ( PyMac_FindResourceModule(name, buf) ) {
  460.             static struct filedescr resfiledescr = { "", "", PY_RESOURCE};
  461.             
  462.             return &resfiledescr;
  463.         }
  464. #endif
  465. #ifdef _AMIGA
  466.         AddPart(buf,name,MAXPATHLEN);
  467.         len=strlen(buf);
  468. #else
  469.         if (len > 0 && buf[len-1] != SEP)
  470.             buf[len++] = SEP;
  471. #ifdef IMPORT_8x3_NAMES
  472.         /* see if we are searching in directory dos_8x3 */
  473.         if (len > 7 && !strncmp(buf + len - 8, "dos_8x3", 7)){
  474.             int j;
  475.             char ch;  /* limit name to eight lower-case characters */
  476.             for (j = 0; (ch = name[j]) && j < 8; j++)
  477.                 if (isupper(ch))
  478.                     buf[len++] = tolower(ch);
  479.                 else
  480.                     buf[len++] = ch;
  481.         }
  482.         else /* Not in dos_8x3, use the full name */
  483. #endif
  484.         {
  485.             strcpy(buf+len, name);
  486.             len += namelen;
  487.         }
  488. #endif /* _AMIGA */
  489.         for (fdp = import_filetab; fdp->suffix != NULL; fdp++) {
  490.             strcpy(buf+len, fdp->suffix);
  491.             if (verbose > 1)
  492.                 fprintf(stderr, "# trying %s\n", buf);
  493.             fp = fopen(buf, fdp->mode);
  494.             if (fp != NULL)
  495.                 break;
  496.         }
  497.         if (fp != NULL)
  498.             break;
  499.     }
  500.     if (fp == NULL) {
  501.         char buf[256];
  502.         sprintf(buf, "No module named %.200s", name);
  503.         err_setstr(ImportError, buf);
  504.         return NULL;
  505.     }
  506.  
  507.     *p_fp = fp;
  508.     return fdp;
  509. }
  510.  
  511.  
  512. /* Load an external module using the default search path and return
  513.    its module object WITH INCREMENTED REFERENCE COUNT */
  514.  
  515. static object *
  516. load_module(name)
  517.     char *name;
  518. {
  519.     char buf[MAXPATHLEN+1];
  520.     struct filedescr *fdp;
  521.     FILE *fp = NULL;
  522.     object *m;
  523.  
  524.     fdp = find_module(name, (object *)NULL, buf, MAXPATHLEN+1, &fp);
  525.     if (fdp == NULL)
  526.         return NULL;
  527.  
  528.     switch (fdp->type) {
  529.  
  530.     case PY_SOURCE:
  531.         m = load_source_module(name, buf, fp);
  532.         break;
  533.  
  534.     case PY_COMPILED:
  535.         m = load_compiled_module(name, buf, fp);
  536.         break;
  537.  
  538.     case C_EXTENSION:
  539.         m = load_dynamic_module(name, buf, fp);
  540.         break;
  541.  
  542. #ifdef macintosh
  543.     case PY_RESOURCE:
  544.         m = PyMac_LoadResourceModule(name, buf);
  545.         break;
  546. #endif
  547.  
  548.     default:
  549.         err_setstr(SystemError,
  550.                "find_module returned unexpected result");
  551.         m = NULL;
  552.  
  553.     }
  554.     if ( fp )
  555.         fclose(fp);
  556.  
  557.     return m;
  558. }
  559.  
  560.  
  561. /* Initialize a built-in module.
  562.    Return 1 for succes, 0 if the module is not found, and -1 with
  563.    an exception set if the initialization failed. */
  564.  
  565. static int
  566. init_builtin(name)
  567.     char *name;
  568. {
  569.     int i;
  570.     for (i = 0; inittab[i].name != NULL; i++) {
  571.         if (strcmp(name, inittab[i].name) == 0) {
  572.             if (inittab[i].initfunc == NULL) {
  573.                 err_setstr(ImportError,
  574.                        "Cannot re-init internal module");
  575.                 return -1;
  576.             }
  577.             if (verbose)
  578.                 fprintf(stderr, "import %s # builtin\n",
  579.                     name);
  580.             (*inittab[i].initfunc)();
  581.             if (err_occurred())
  582.                 return -1;
  583.             return 1;
  584.         }
  585.     }
  586.     return 0;
  587. }
  588.  
  589.  
  590. /* Frozen modules */
  591.  
  592. static struct _frozen *
  593. find_frozen(name)
  594.     char *name;
  595. {
  596.     struct _frozen *p;
  597.  
  598.     for (p = frozen_modules; ; p++) {
  599.         if (p->name == NULL)
  600.             return NULL;
  601.         if (strcmp(p->name, name) == 0)
  602.             break;
  603.     }
  604.     return p;
  605. }
  606.  
  607. static object *
  608. get_frozen_object(name)
  609.     char *name;
  610. {
  611.     struct _frozen *p = find_frozen(name);
  612.  
  613.     if (p == NULL) {
  614.         err_setstr(ImportError, "No such frozen object");
  615.         return NULL;
  616.     }
  617.     return rds_object((char *)p->code, p->size);
  618. }
  619.  
  620. /* Initialize a frozen module.
  621.    Return 1 for succes, 0 if the module is not found, and -1 with
  622.    an exception set if the initialization failed.
  623.    This function is also used from frozenmain.c */
  624.  
  625. int
  626. init_frozen(name)
  627.     char *name;
  628. {
  629.     struct _frozen *p = find_frozen(name);
  630.     object *co;
  631.     object *m;
  632.  
  633.     if (p == NULL)
  634.         return 0;
  635.     if (verbose)
  636.         fprintf(stderr, "import %s # frozen\n", name);
  637.     co = rds_object((char *)p->code, p->size);
  638.     if (co == NULL)
  639.         return -1;
  640.     if (!is_codeobject(co)) {
  641.         DECREF(co);
  642.         err_setstr(TypeError, "frozen object is not a code object");
  643.         return -1;
  644.     }
  645.     m = exec_code_module(name, co);
  646.     DECREF(co);
  647.     if (m == NULL)
  648.         return -1;
  649.     DECREF(m);
  650.     return 1;
  651. }
  652.  
  653.  
  654. /* Import a module, either built-in, frozen, or external, and return
  655.    its module object WITH INCREMENTED REFERENCE COUNT */
  656.  
  657. object *
  658. import_module(name)
  659.     char *name;
  660. {
  661.     object *m;
  662.  
  663.     if (import_modules == NULL) {
  664.         err_setstr(SystemError, "sys.modules has been deleted");
  665.         return NULL;
  666.     }
  667.     if ((m = dictlookup(import_modules, name)) != NULL) {
  668.         INCREF(m);
  669.     }
  670.     else {
  671.         int i;
  672.         if ((i = init_builtin(name)) || (i = init_frozen(name))) {
  673.             if (i < 0)
  674.                 return NULL;
  675.             if ((m = dictlookup(import_modules, name)) == NULL) {
  676.                 if (err_occurred() == NULL)
  677.                     err_setstr(SystemError,
  678.                  "built-in module not initialized properly");
  679.             }
  680.             else
  681.                 INCREF(m);
  682.         }
  683.         else
  684.             m = load_module(name);
  685.     }
  686.  
  687.     return m;
  688. }
  689.  
  690.  
  691. /* Re-import a module of any kind and return its module object, WITH
  692.    INCREMENTED REFERENCE COUNT */
  693.  
  694. object *
  695. reload_module(m)
  696.     object *m;
  697. {
  698.     char *name;
  699.     int i;
  700.  
  701.     if (m == NULL || !is_moduleobject(m)) {
  702.         err_setstr(TypeError, "reload() argument must be module");
  703.         return NULL;
  704.     }
  705.     name = getmodulename(m);
  706.     if (name == NULL)
  707.         return NULL;
  708.     if (import_modules == NULL) {
  709.         err_setstr(SystemError, "sys.modules has been deleted");
  710.         return NULL;
  711.     }
  712.     if (m != dictlookup(import_modules, name)) {
  713.         err_setstr(ImportError, "reload() module not in sys.modules");
  714.         return NULL;
  715.     }
  716.     /* Check for built-in and frozen modules */
  717.     if ((i = init_builtin(name)) || (i = init_frozen(name))) {
  718.         if (i < 0)
  719.             return NULL;
  720.         INCREF(m);
  721.     }
  722.     else
  723.         m = load_module(name);
  724.     return m;
  725. }
  726.  
  727.  
  728. /* Module 'imp' provides Python access to the primitives used for
  729.    importing modules.
  730. */
  731.  
  732. static object *
  733. imp_get_magic(self, args)
  734.     object *self;
  735.     object *args;
  736. {
  737.     char buf[4];
  738.  
  739.     if (!newgetargs(args, ""))
  740.         return NULL;
  741.     buf[0] = (MAGIC >>  0) & 0xff;
  742.     buf[1] = (MAGIC >>  8) & 0xff;
  743.     buf[2] = (MAGIC >> 16) & 0xff;
  744.     buf[3] = (MAGIC >> 24) & 0xff;
  745.  
  746.     return newsizedstringobject(buf, 4);
  747. }
  748.  
  749. static object *
  750. imp_get_suffixes(self, args)
  751.     object *self;
  752.     object *args;
  753. {
  754.     object *list;
  755.     struct filedescr *fdp;
  756.  
  757.     if (!newgetargs(args, ""))
  758.         return NULL;
  759.     list = newlistobject(0);
  760.     if (list == NULL)
  761.         return NULL;
  762.     for (fdp = import_filetab; fdp->suffix != NULL; fdp++) {
  763.         object *item = mkvalue("ssi",
  764.                        fdp->suffix, fdp->mode, fdp->type);
  765.         if (item == NULL) {
  766.             DECREF(list);
  767.             return NULL;
  768.         }
  769.         if (addlistitem(list, item) < 0) {
  770.             DECREF(list);
  771.             DECREF(item);
  772.             return NULL;
  773.         }
  774.         DECREF(item);
  775.     }
  776.     return list;
  777. }
  778.  
  779. static object *
  780. imp_find_module(self, args)
  781.     object *self;
  782.     object *args;
  783. {
  784.     extern int fclose PROTO((FILE *));
  785.     char *name;
  786.     object *path = NULL;
  787.     object *fob, *ret;
  788.     struct filedescr *fdp;
  789.     char pathname[MAXPATHLEN+1];
  790.     FILE *fp;
  791.     if (!newgetargs(args, "s|O!", &name, &Listtype, &path))
  792.         return NULL;
  793.     fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
  794.     if (fdp == NULL)
  795.         return NULL;
  796.     fob = newopenfileobject(fp, pathname, fdp->mode, fclose);
  797.     if (fob == NULL) {
  798.         fclose(fp);
  799.         return NULL;
  800.     }
  801.     ret = mkvalue("Os(ssi)",
  802.               fob, pathname, fdp->suffix, fdp->mode, fdp->type);
  803.     DECREF(fob);
  804.     return ret;
  805. }
  806.  
  807. static object *
  808. imp_init_builtin(self, args)
  809.     object *self;
  810.     object *args;
  811. {
  812.     char *name;
  813.     int ret;
  814.     object *m;
  815.     if (!newgetargs(args, "s", &name))
  816.         return NULL;
  817.     ret = init_builtin(name);
  818.     if (ret < 0)
  819.         return NULL;
  820.     if (ret == 0) {
  821.         INCREF(None);
  822.         return None;
  823.     }
  824.     m = add_module(name);
  825.     XINCREF(m);
  826.     return m;
  827. }
  828.  
  829. static object *
  830. imp_init_frozen(self, args)
  831.     object *self;
  832.     object *args;
  833. {
  834.     char *name;
  835.     int ret;
  836.     object *m;
  837.     if (!newgetargs(args, "s", &name))
  838.         return NULL;
  839.     ret = init_frozen(name);
  840.     if (ret < 0)
  841.         return NULL;
  842.     if (ret == 0) {
  843.         INCREF(None);
  844.         return None;
  845.     }
  846.     m = add_module(name);
  847.     XINCREF(m);
  848.     return m;
  849. }
  850.  
  851. static object *
  852. imp_get_frozen_object(self, args)
  853.     object *self;
  854.     object *args;
  855. {
  856.     char *name;
  857.  
  858.     if (!newgetargs(args, "s", &name))
  859.         return NULL;
  860.     return get_frozen_object(name);
  861. }
  862.  
  863. static object *
  864. imp_is_builtin(self, args)
  865.     object *self;
  866.     object *args;
  867. {
  868.     int i;
  869.     char *name;
  870.     if (!newgetargs(args, "s", &name))
  871.         return NULL;
  872.     for (i = 0; inittab[i].name != NULL; i++) {
  873.         if (strcmp(name, inittab[i].name) == 0) {
  874.             if (inittab[i].initfunc == NULL)
  875.                 return newintobject(-1);
  876.             else
  877.                 return newintobject(1);
  878.         }
  879.     }
  880.     return newintobject(0);
  881. }
  882.  
  883. static object *
  884. imp_is_frozen(self, args)
  885.     object *self;
  886.     object *args;
  887. {
  888.     struct _frozen *p;
  889.     char *name;
  890.     if (!newgetargs(args, "s", &name))
  891.         return NULL;
  892.     for (p = frozen_modules; ; p++) {
  893.         if (p->name == NULL)
  894.             break;
  895.         if (strcmp(p->name, name) == 0)
  896.             return newintobject(1);
  897.     }
  898.     return newintobject(0);
  899. }
  900.  
  901. static FILE *
  902. get_file(pathname, fob, mode)
  903.     char *pathname;
  904.     object *fob;
  905.     char *mode;
  906. {
  907.     FILE *fp;
  908.     if (fob == NULL) {
  909.         fp = fopen(pathname, mode);
  910.         if (fp == NULL)
  911.             err_errno(IOError);
  912.     }
  913.     else {
  914.         fp = getfilefile(fob);
  915.         if (fp == NULL)
  916.             err_setstr(ValueError, "bad/closed file object");
  917.     }
  918.     return fp;
  919. }
  920.  
  921. static object *
  922. imp_load_compiled(self, args)
  923.     object *self;
  924.     object *args;
  925. {
  926.     char *name;
  927.     char *pathname;
  928.     object *fob = NULL;
  929.     object *m;
  930.     FILE *fp;
  931.     if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob))
  932.         return NULL;
  933.     fp = get_file(pathname, fob, "rb");
  934.     if (fp == NULL)
  935.         return NULL;
  936.     m = load_compiled_module(name, pathname, fp);
  937.     return m;
  938. }
  939.  
  940. static object *
  941. imp_load_dynamic(self, args)
  942.     object *self;
  943.     object *args;
  944. {
  945.     char *name;
  946.     char *pathname;
  947.     object *fob = NULL;
  948.     object *m;
  949.     FILE *fp = NULL;
  950.     if (!newgetargs(args, "ss|O!", &name, &pathname, &Filetype, &fob))
  951.         return NULL;
  952.     if (fob)
  953.         fp = get_file(pathname, fob, "r");
  954.     m = load_dynamic_module(name, pathname, fp);
  955.     return m;
  956. }
  957.  
  958. static object *
  959. imp_load_source(self, args)
  960.     object *self;
  961.     object *args;
  962. {
  963.     char *name;
  964.     char *pathname;
  965.     object *fob = NULL;
  966.     object *m;
  967.     FILE *fp;
  968.     if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob))
  969.         return NULL;
  970.     fp = get_file(pathname, fob, "r");
  971.     if (fp == NULL)
  972.         return NULL;
  973.     m = load_source_module(name, pathname, fp);
  974.     return m;
  975. }
  976.  
  977. #ifdef macintosh
  978. static object *
  979. imp_load_resource(self, args)
  980.     object *self;
  981.     object *args;
  982. {
  983.     char *name;
  984.     char *pathname;
  985.     object *m;
  986.  
  987.     if (!newgetargs(args, "ss", &name, &pathname))
  988.         return NULL;
  989.     m = PyMac_LoadResourceModule(name, pathname);
  990.     return m;
  991. }
  992. #endif /* macintosh */
  993.  
  994. static object *
  995. imp_new_module(self, args)
  996.     object *self;
  997.     object *args;
  998. {
  999.     char *name;
  1000.     if (!newgetargs(args, "s", &name))
  1001.         return NULL;
  1002.     return newmoduleobject(name);
  1003. }
  1004.  
  1005. static struct methodlist imp_methods[] = {
  1006.     {"get_frozen_object",    imp_get_frozen_object,    1},
  1007.     {"get_magic",        imp_get_magic,        1},
  1008.     {"get_suffixes",    imp_get_suffixes,    1},
  1009.     {"find_module",        imp_find_module,    1},
  1010.     {"init_builtin",    imp_init_builtin,    1},
  1011.     {"init_frozen",        imp_init_frozen,    1},
  1012.     {"is_builtin",        imp_is_builtin,        1},
  1013.     {"is_frozen",        imp_is_frozen,        1},
  1014.     {"load_compiled",    imp_load_compiled,    1},
  1015.     {"load_dynamic",    imp_load_dynamic,    1},
  1016.     {"load_source",        imp_load_source,    1},
  1017.     {"new_module",        imp_new_module,        1},
  1018. #ifdef macintosh
  1019.     {"load_resource",    imp_load_resource,    1},
  1020. #endif
  1021.     {NULL,            NULL}        /* sentinel */
  1022. };
  1023.  
  1024. void
  1025. initimp()
  1026. {
  1027.     object *m, *d, *v;
  1028.  
  1029.     m = initmodule("imp", imp_methods);
  1030.     d = getmoduledict(m);
  1031.  
  1032.     v = newintobject(SEARCH_ERROR);
  1033.     dictinsert(d, "SEARCH_ERROR", v);
  1034.     XDECREF(v);
  1035.  
  1036.     v = newintobject(PY_SOURCE);
  1037.     dictinsert(d, "PY_SOURCE", v);
  1038.     XDECREF(v);
  1039.  
  1040.     v = newintobject(PY_COMPILED);
  1041.     dictinsert(d, "PY_COMPILED", v);
  1042.     XDECREF(v);
  1043.  
  1044.     v = newintobject(C_EXTENSION);
  1045.     dictinsert(d, "C_EXTENSION", v);
  1046.     XDECREF(v);
  1047.  
  1048. #ifdef macintosh
  1049.     v = newintobject(PY_RESOURCE);
  1050.     dictinsert(d, "PY_RESOURCE", v);
  1051.     XDECREF(v);
  1052. #endif
  1053.  
  1054.  
  1055.     if (err_occurred())
  1056.         fatal("imp module initialization failed");
  1057. }
  1058.